<?php

namespace XWAM\Addon\POrgCustomer\Controller;

/**
 * CustomerController 类
 *
 * @since 1.0 <2015-12-5> SoChishun <14507247@qq.com> Added.
 */
class CustomerAppointmentController extends AddonbaseController {

    /**
     * 获取客户列表搜索数据
     * @return array
     * @since 1.0 2014-12-30 by sutroon
     */
    function customer_list_get_search() {
        $search = $_GET;
        if (!empty($search['telphone'])) {
            $where['telphone'] = array('like', '%' . $search['tel']);
        }
        if (!empty($search['name'])) {
            $where['name'] = array('like', '%' . $search['name'] . '%');
        }
        if (!empty($search['serial_no'])) {
            $where['serial_no'] = $search['serial_no'];
        }
        if (!empty($search['buy_count'])) {
            $where['buy_count'] = array('GT', $search['buy_count']);
        }
        if (!empty($search['total_amount'])) {
            $where['total_amount'] = array('GT', $search['total_amount']);
        }
        if ($this->user_login_data['type_name']=='SEAT') {
            $where['user_name']=$this->user_login_data['user_name'];
        }
        return array('search' => $search, 'where' => $where);
    }

    // 客户列表
    public function customer_list() {
        $asearch_info = $this->customer_list_get_search();
        if (I('action') == 'export') {
            $list = M('v_porg_customer_appointment')->field("name as '客户姓名', telphone as '电话号码', address as '联系地址', serial_no as '客户编号', buy_count as '购买次数', total_amount as '累计消费', buy_time as '上次购买时间', user_name as '工号', create_time as '创建时间'")->where($asearch_info['where'])->select();
            if (!$list) {
                $this->error('找不到符合条件的记录!');
            }
            sofn_excel_export($list);
        } else {
            $list = D('Common')->get_paging_list($asearch_info['where'], $show, array('ORDERBY' => 'id desc', 'PAGEPARAMS' => $asearch_info['search'], 'TABLE' => 'v_porg_customer_appointment'));
            $this->assign('page', $show);
            $this->assign('list', $list);
            $this->assign('search', $asearch_info['search']);
            $this->display_cpp();
        }
    }

    // 预约回访 2014-12-24 by sutroon
    public function appointment_edit($id = 0, $customer_id = 0) {
        if (!$customer_id) {
            $this->dialogClose(false, '参数有误!');
        }

        $data = AddonD('Customer')->field('id as customer_id, `name`, serial_no')->find($customer_id);
        if (!$data) {
            $this->dialogClose(false, '客户不存在!');
        }
        if ($id) {
            $data2 = AddonD('CustomerAppointment')->find($id);
            $data = array_merge($data, $data2);
        }
        $list = AddonD('CustomerAppointment')->where(array('customer_id' => $customer_id))->select();
        $this->assign('data', $data);
        $this->assign('list', $list);
        $this->display();
    }

    // 预约回访数据保存 2014-12-24 by sutroon
    public function appointment_edit_save($id = 0, $customerID = 0) {
        $result = AddonD('CustomerAppointment')->save_appointment();
        $this->dialogJump($result['status'], $result['info']);
    }

    // 客户调度记录 2014-12-25 by sutroon
    public function dispatch_log_list() {
        $customerID = I('customerID');
        if (!$customerID) {
            $this->act_close_dialog(false, '参数有误!');
        }
        $list = M('vcustomer_dispatch')->where("customerID=$customerID")->select();
        $this->assign('list', $list);
        $this->display2();
    }

    // 获取客户调度查询表单数据 2014-12-25 by sutroon
    function dispatch_edit_get_search() {
        $search['lastBuyTimeExpBegin'] = I('lastBuyTimeExpBegin');
        $search['lastBuyTimeBegin'] = I('lastBuyTimeBegin');
        $search['lastBuyTimeExpEnd'] = I('lastBuyTimeExpEnd');
        $search['lastBuyTimeEnd'] = I('lastBuyTimeEnd');
        $search['lastVisitTimeExpBegin'] = I('lastVisitTimeExpBegin');
        $search['lastVisitTimeBegin'] = I('lastVisitTimeBegin');
        $search['lastVisitTimeExpEnd'] = I('lastVisitTimeExpEnd');
        $search['lastVisitTimeEnd'] = I('lastVisitTimeEnd');
        $search['buyCountExp'] = I('buyCountExp');
        $search['buyCount'] = I('buyCount');
        $search['cumulativeAmountExp'] = I('cumulativeAmountExp');
        $search['cumulativeAmount'] = I('cumulativeAmount');
        $search['oldUsers'] = I('oldUsers');
        $search['buyCountState'] = I('buyCountState');
        $search['searchNumber'] = I('searchNumber');
        if ($search['lastBuyTimeExpBegin'] && $search['lastBuyTimeBegin']) {
            $where['lastBuyTime'] = array($search['lastBuyTimeExpBegin'], $search['lastBuyTimeBegin']);
        }
        if ($search['lastBuyTimeExpEnd'] && $search['lastBuyTimeEnd']) {
            if (isset($where['lastBuyTime'])) {
                $where['lastBuyTime'] = array($where['lastBuyTime'], array($search['lastBuyTimeExpEnd'], $search['lastBuyTimeEnd']));
            } else {
                $where['lastBuyTime'] = array($search['lastBuyTimeExpEnd'], $search['lastBuyTimeEnd']);
            }
        }

        if ($search['lastVisitTimeExpBegin'] && $search['lastVisitTimeBegin']) {
            $where['lastVisitTime'] = array($search['lastVisitTimeExpBegin'], $search['lastVisitTimeBegin']);
        }
        if ($search['lastVisitTimeExpEnd'] && $search['lastVisitTimeEnd']) {
            if (isset($where['lastVisitTime'])) {
                $where['lastVisitTime'] = array($where['lastVisitTime'], array($search['lastVisitTimeExpEnd'], $search['lastVisitTimeEnd']));
            } else {
                $where['lastVisitTime'] = array($search['lastVisitTimeExpEnd'], $search['lastVisitTimeEnd']);
            }
        }
        if ($search['buyCount'] && $search['buyCountExp']) {
            $where['buyCount'] = array($search['buyCountExp'], $search['buyCount']);
        }
        if (strlen($search['buyCountState']) > 0) {
            switch ($search['buyCountState']) {
                case '1':
                    $where['buyCount'] = array('GT', 0);
                    break;
                case '0':
                    $where['buyCount'] = array('EQ', 0);
                    break;
                case '2':
                    if ($where['buyCount']) {
                        unset($where['buyCount']);
                    }
                    break;
            }
        }
        if ($search['cumulativeAmount'] && $search['cumulativeAmountExp']) {
            $where['cumulativeAmount'] = array($search['cumulativeAmountExp'], $search['cumulativeAmount']);
        }
        if ($search['oldUsers']) {
            $search['oldUsers'] = str_replace("'", '', $search['oldUsers']);
            $search['oldUsers'] = str_replace(' ', '', $search['oldUsers']);
            $search['oldUsers'] = str_replace(",", "','", $search['oldUsers']);
            $uids = M('tuser')->where("userType='SEAT' and userName in ('" . $search['oldUsers'] . "')")->getField('id', true);
            if ($uids) {
                $where['userID'] = array('IN', $uids);
            }
        }
        return array('search' => $search, 'where' => $where);
    }

    // 客户调度 2014-12-25 by sutroon
    public function dispatch_edit() {
        $this->checkUPR('调度客户');
        $customerID = I('customerID');
        if ($customerID) {
            $search = false;
            $where['id'] = $customerID;
        } else {
            $arr = $this->dispatch_edit_get_search();
            $search = $arr['search'];
            $where = $arr['where'];
        }
        $count = 0;
        $hasOrderCount = 0;
        if ($where) {
            if ($this->RoleInfo['SEAT']) {
                $where['userID'] = $this->loginData['id'];
            } else if ($this->RoleInfo['ADMIN']) {
                $where['siteID'] = $this->loginData['siteID'];
            }
            $M = M('tcustomer');
            if ($search['searchNumber']) {
                $M->limit($search['searchNumber']);
            }
            $list = $M->where($where)->field('id, personalName, buyCount, userID')->select();
            if ($list) {
                $count = count($list);
                foreach ($list as $row) {
                    if ($row['buyCount'] > 0) {
                        $hasOrderCount++;
                    }
                }
            }
        }
        $this->assign('count', $count);
        $this->assign('hasOrderCount', $hasOrderCount);
        $this->assign('list', $list);
        $this->assign('search', $search);
        $this->assign('UPR', $this->UPR);
        $this->display();
    }

    // 客户调度数据保存 2014-12-25 by sutroon
    public function dispatch_edit_save() {
        $this->checkUPR('调度客户');
        $ids = I('ids');
        if (!$ids) {
            $this->act_error('未选择客户!');
        }
        $newUsers = I('newUsers');
        if ($newUsers) {
            $newUsers = str_replace("'", '', $newUsers);
            $newUsers = str_replace(' ', '', $newUsers);
            $newUsers = str_replace(',', "','", $newUsers);
        }
        if (!$newUsers) {
            $this->act_error('新工号未填写');
        }
        $siteID = $this->loginData['siteID'];
        $M = M('tuser');
        $arrUsers = $M->where("userName in ('$newUsers') and userType='SEAT'")->getField('id', true);
        if (!$arrUsers) {
            $this->act_error("新工号['$newUsers']不是有效座席!");
        }
        $perNumber = I('perNumber');
        if (!$perNumber || !is_numeric($perNumber) || $perNumber < 1) {
            $perNumber = ceil(count($ids) / count($arrUsers));
        }
        $remark = I('remark');
        $adminID = $this->loginData['id'];
        $name = date('Ymd-his-') . $adminID;
        $i = 0;
        $n = 0;
        $sql = "insert into tcustomer_dispatch (`name`, customerID, oldUserID, userID, adminID, remark, siteID) values";
        $sqls = false;
        foreach ($ids as $ele) {
            $arrEle = explode('/', $ele);
            $userID = $arrUsers[$n];
            $sqls[] = "('$name', " . $arrEle[0] . ", " . $arrEle[1] . ", $userID, $adminID, '$remark', $siteID)";
            if ($i % $perNumber == 0) {
                $n++;
            }
            $i++;
            if ($i > 0 && ($i % 300 == 0)) {
                $sqltemp = $sql . implode(',', $sqls);
                // echo '<br />' . $sqltemp;
                $result = $M->execute($sqltemp);
                if (false === $result) {
                    die($M->getDbError());
                }
                empty($sqls);
                sleep(2);
            }
        }
        if ($sqls) {
            $sqltemp = $sql . implode(',', $sqls);
            // echo '<br />' . $sqltemp;
            $result = $M->execute($sqltemp);
            if (false === $result) {
                die($M->getDbError());
            }
        }
        $result = mysql_query("call proc_customer_dispatch('$name',@result)");
        if (false === $result) {
            die(mysql_error());
        }
        $result = mysql_query('select @result');
        $arrCode = mysql_fetch_array($result);
        if (false === $arrCode) {
            die(mysql_error());
        }
        $this->act_close_dialog($arrCode['@result'] == '1', sofunc_get_procedure_result_text($arrCode['@result']));
    }

}
